package com.lanou.myim.ui.fragment;

import java.util.List;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;

import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.easemob.chat.EMContactListener;
import com.easemob.chat.EMContactManager;
import com.lanou.myim.R;


import com.lanou.myim.entity.EventBusConstant;

import com.lanou.myim.entity.FriendsEty;
import com.lanou.myim.entity.MsgFromEty;
import com.lanou.myim.presenter.FriendsPresenter;
import com.lanou.myim.presenter.FriendsPresenterInterface;
import com.lanou.myim.ui.SideBar;
import com.lanou.myim.adapter.SortAdapter;
import com.lanou.myim.model.SortModel;
import com.lanou.myim.tools.ParseSingleton;
import com.lanou.myim.ui.activity.AddFriendsActivity;
import com.lanou.myim.ui.activity.ApplyActivity;
import com.lanou.myim.ui.activity.ChatRoomActivity;
import com.lanou.myim.ui.activity.GroupActivity;
import com.lanou.myim.ui.activity.PrivateChatActivity;


import de.greenrobot.event.EventBus;


public class FriendsFragment extends BaseFragment implements FriendsFragmentInterface, View.OnClickListener {
    private ListView sortListView;
    private SideBar sideBar;
    private TextView dialog;
    private SortAdapter adapter;
    private EditText mClearEditText;
    private RelativeLayout relativeLayout, relativeLayout_apply, linkman_liaotianshi;
    private ImageView imageView;


    private ImageView informUp;


    View sortListViewHead;
    FriendsPresenterInterface friendsPresenterInterface;


    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 1){
                friendsPresenterInterface.receiveApply((String) msg.obj, "加个好友吧");
            }else if (msg.what == 2){
                friendsPresenterInterface.deletedByFriend();
            }else if (msg.what == 3){
                friendsPresenterInterface.applySuccessed((String)msg.obj);
            }else if (msg.what == 4){
                friendsPresenterInterface.friendIncreased(((FriendsEty)msg.obj).getNames());
            }
            return false;
        }
    });



    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_friends, null);
        friendsPresenterInterface = new FriendsPresenter(this);
        initViews(view);
        return view;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        adapter = new SortAdapter(getActivity(), friendsPresenterInterface.getFriendList());
        sortListView.setAdapter(adapter);

        sortListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position != 0) {
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("ID", new MsgFromEty("FRIEND", ((SortModel) adapter.getItem(position - 1)).getName(), null, null));
                    intent.setClass(getActivity(), PrivateChatActivity.class);
                    intent.putExtras(bundle);
                    getActivity().startActivity(intent);
                }
            }
        });


        sortListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                return false;
            }
        });


        sortListView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {

                menu.add(0, 0, 0, "删除联系人");
                menu.add(0, 1, 0, "移至黑名单");
                menu.add(0, 2, 0, "设置备注");
            }
        });



        EMContactManager.getInstance().setContactListener(new EMContactListener() {

            @Override
            public void onContactAgreed(String username) {
                //好友请求被同意
                Message message = new Message();
                message.what = 3;
                message.obj =  username;
                handler.sendMessage(message);
            }

            @Override
            public void onContactRefused(String username) {
                //好友请求被拒绝
            }

            @Override
            public void onContactInvited(String username, String reason) {
                //收到好友邀请
                Message message = new Message();
                message.what = 1;
                message.obj =  username;
                handler.sendMessage(message);
            }

            @Override
            public void onContactDeleted(List<String> usernameList) {
                //被删除时回调此方法
                Message message = new Message();
                message.what = 2;
                handler.sendMessage(message);
            }


            @Override
            public void onContactAdded(List<String> usernameList) {
                //增加了联系人时回调此方法
                Message message = new Message();
                message.what = 4;
                FriendsEty friendEty = new FriendsEty();
                friendEty.setNames(usernameList);
                message.obj = friendEty;
                handler.sendMessage(message);
            }
        });






    }


    @Override
    public boolean onContextItemSelected(MenuItem item) {


        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
                .getMenuInfo();
        final int MID = (int) info.id;// 这里的info.id对应的就是数据库中_id的值
        if (MID >= 0){
        switch (item.getItemId()) {
            case 0:
                friendsPresenterInterface.deleteFriend(((SortModel) adapter.getItem(MID)).getName());
                break;

            case 1:
                  friendsPresenterInterface.addFriendToBlackList(((SortModel) adapter.getItem(MID)).getName(), false);
                break;

            case 2:
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                View view = LayoutInflater.from(getActivity()).inflate(R.layout.editbox, null);
                final EditText editText = (EditText) view.findViewById(R.id.publish_editText);
                builder.setTitle("备注名称:").setView(view).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                       String name = editText.getText().toString();
                        if (name.length() == 0){
                            Toast.makeText(getActivity(), "备注名称不能为空", Toast.LENGTH_SHORT).show();
                        }else {
                            ParseSingleton.insertOrModifyDescr(((SortModel) adapter.getItem(MID)).getName(),name);
                            adapter.notifyDataSetChanged();
                            EventBus.getDefault().post(EventBusConstant.REFRESH_REMARKS);
                        }
                    }
                }).setNegativeButton("取消", null).create().show();
                break;

            default:
                break;
        }
        }

        return super.onContextItemSelected(item);
    }

    private void initViews(View view) {

        mClearEditText = (EditText) view.findViewById(R.id.filter_edit);
        sideBar = (SideBar) view.findViewById(R.id.sidrbar);
        dialog = (TextView) view.findViewById(R.id.dialog);
        sideBar.setTextView(dialog);


        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {

                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    sortListView.setSelection(position);
                }

            }
        });

        sortListView = (ListView) view.findViewById(R.id.country_lvcountry);
        sortListViewHead = LayoutInflater.from(getActivity()).inflate(R.layout.fragement_friends_head, null, false);
        sortListView.addHeaderView(sortListViewHead);
        relativeLayout = (RelativeLayout) view.findViewById(R.id.linkman_qunliao);
        imageView = (ImageView) view.findViewById(R.id.tv_add_friends);
        relativeLayout_apply = (RelativeLayout) view.findViewById(R.id.linkman_apply);
        linkman_liaotianshi = (RelativeLayout) view.findViewById(R.id.linkman_liaotianshi);
        linkman_liaotianshi.setOnClickListener(this);
        relativeLayout_apply.setOnClickListener(this);
        relativeLayout.setOnClickListener(this);
        imageView.setOnClickListener(this);

        informUp = (ImageView) view.findViewById(R.id.iv_friend_inform);



        mClearEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                friendsPresenterInterface.searchFriends(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }


    @Override
    public void refreshList(List<SortModel> sortModels) {
        adapter.updateListView(sortModels);
    }

    @Override
    public void showRed() {
        informUp.setVisibility(View.VISIBLE);
        EventBus.getDefault().post(EventBusConstant.SHOW_FRIEND_INFORM);
    }

    @Override
    public void dismissRed() {
        informUp.setVisibility(View.GONE);
        EventBus.getDefault().post(EventBusConstant.DISMISS_FRIEND_INFORM);
    }

    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.linkman_qunliao:
                intent = new Intent(getActivity(), GroupActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_add_friends:
                intent = new Intent(getActivity(), AddFriendsActivity.class);
                startActivity(intent);
                break;
            case R.id.linkman_apply:
                dismissRed();
                intent = new Intent(getActivity(), ApplyActivity.class);
                startActivity(intent);
                break;
            case R.id.linkman_liaotianshi:
                intent = new Intent(getActivity(), ChatRoomActivity.class);
                startActivity(intent);
                break;
        }
    }
}
